package com.frame.jfinal.render;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import javax.servlet.ServletOutputStream;

import com.frame.util.ValidateCodeImageUtil;
import com.jfinal.render.Render;

/*******************************************
 * 作用描述：返回验证码
 *******************************************
 * @author LRC
 * @createDate 2015-9-11
 * @version v1.0 
 * @updateRecord 格式：时间，作者，修改说明
 *******************************************
 * 
 */
public class RenderValidateCode extends Render {
	private String codeName = "validateCode";
	public RenderValidateCode(){
		
	}
	public RenderValidateCode(String codeName) {
		this.codeName = codeName;
	}
	@Override
	public void render() {
		ServletOutputStream sos = null;
        try {
            //设置头信息,内容处理的方式,attachment以附件的形式打开,就是进行下载,并设置下载文件的命名
        	//response.setHeader("Content-Disposition","attachment;filename="+file.getName());
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/jpeg");
            //response.setContentType("image/png");
            sos=response.getOutputStream();
            //获取图片Map
    		Map<String, BufferedImage> imageMap = ValidateCodeImageUtil.createImage();
    		//获取验证码与图片
    		String key = imageMap.keySet().iterator().next();
    		request.getSession().setAttribute(codeName, key.toUpperCase());
    		BufferedImage image = imageMap.get(key);
    		//获取输入流
    		InputStream reader = null;
    		try {
    			reader = ValidateCodeImageUtil.getInputStream(image, "JPEG");
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
            // 创建缓冲区
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = reader.read(buffer)) != -1) {
                sos.write(buffer, 0, len);
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sos != null)
                try {
                    sos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
		
	}

}
